package com.rc.saas.mini.common.upyun;

import com.UpYun;
import com.rc.saas.mini.common.config.UpYunConfig;
import com.upyun.FormUploader;
import com.upyun.Params;
import com.upyun.Result;
import com.upyun.UpException;

import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;

/**
 * https://github.com/upyun/java-sdk
 * 后台上传API
 * FORM API
 * 网页上传,通过网页 FORM，使用 HTTP/HTTPS 直接把文件上传到又拍云存储。
 * 特别地，文中请求参数放在 HTTP/HTTPS body 中传递，请确保您上传表单格式符合 RFC 1867 协议规范
 * Created by sven on 2018-03-18
 */
public class WebUploader {
    private UpYun upyun;
    private FormUploader formUploader;
    private static WebUploader singleton = null;

    //服务器保存路径
    //访问路径：http://jzimage.test.upcdn.net/up/tt/bohcz1gjvqw0q82p2dm420zd7r3h8fia.png
    //final static String UPLOAD_PATH = "/enterprise/image";

    //@Autowired
    //private UpYunConfig upYunConfig;

    //public WebUploader(UpYunConfig upYunConfig) {
    //    this.formUploader = new FormUploader(upYunConfig.getBucketName(), upYunConfig.getUserName(), upYunConfig.getPassword());
    //}

    /**
     * 创建实例,只能使用服务的操作员身份登录，而不是又拍云的登录帐号
     * @param upYunConfig
     */
    private WebUploader(UpYunConfig upYunConfig) {
        this.formUploader = new FormUploader(upYunConfig.getBucketName(), upYunConfig.getUserName(), upYunConfig.getPassword());
        this.upyun = new UpYun(upYunConfig.getBucketName(), upYunConfig.getUserName(), upYunConfig.getPassword());
    }

    /**
     * 懒汉式单例模式
     * @param upYunConfig
     * @return
     */
    public static WebUploader getInstance(UpYunConfig upYunConfig) {
        //如果不存在才真的创建实例
        if (singleton == null) {
            synchronized (WebUploader.class) {
                singleton = new WebUploader(upYunConfig);
            }
        }

        return singleton;
    }

    /**
     * 网页上传文件(表单上传接口)
     *
     * @param pictureFile
     * @return
     * @throws NoSuchAlgorithmException
     * @throws SignatureException
     * @throws InvalidKeyException
     */
    public boolean uploadFile(String uploadPath, File pictureFile) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
        //File file = new File(pictureFile);
        //保存路径,必须设置该参数
        //String savePath = uploadPath + "/{random32}{.suffix}";
        final Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put(Params.SAVE_KEY, uploadPath);

        Result result = formUploader.upload(paramsMap, pictureFile);
        return result.isSucceed();
    }

    /**
     * 删除文件
     *
     * @param uploadPath 文件在又拍云的路径,若 filePath 指定的文件不存在，则返回『文件不存在』的错误
     * @return
     * @throws IOException
     * @throws UpException
     */
    public boolean deleteFile(String uploadPath) throws IOException, UpException {
        return upyun.deleteFile(uploadPath,null);
    }
}
